import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        int len = nums.length;
        if (nums[0] > 0 || nums[len-1] < 0) return ret;
        for (int i = 0; i < len-2; i++) {
            // 如果nums[i]>0，那么后面的数全是大于0的数，所有不可能存在三数之和为0
            if (nums[i] > 0) break;
            // 避免重复
            if (i > 0 && nums[i] == nums[i-1]) continue;
            int target = -nums[i];
            int j = i + 1, k = len-1;
            while (j < k) {
                int sum = nums[j] + nums[k];
                if (sum == target) {
                    ret.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    j++;
                    k--;
                }else if (sum > target) {
                    k--;
                }else {
                    j++;
                }
                while  (j < k && j > i + 1 && nums[j] == nums[j-1]) j++;
                while (j < k && k < len-1 && nums[k] == nums[k+1]) k--;
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        ThreeSum threeSum = new ThreeSum();
        System.out.println(threeSum.threeSum(new int[]{0,0,0,0}));
    }
}
